package br.com.pontoe.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.pontoe.controller.action.Action;
import br.com.pontoe.controller.action.ActionResult;
import br.com.pontoe.controller.action.AtualizarRegistrosAction;
import br.com.pontoe.controller.action.AutenticarAction;
import br.com.pontoe.controller.action.CadastroFuncionarioAction;
import br.com.pontoe.controller.action.ConsultarRegistrosAction;
import br.com.pontoe.controller.action.PesquisarFuncionarioAction;
import br.com.pontoe.controller.action.RegistrarPontoAction;
import br.com.pontoe.controller.action.FuncionarioAction;

/**
 * @author Cleison
 */
public class Controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Map<String, Action> mapActions = new HashMap<String, Action>();
	
	@Override
	public void init() throws ServletException {
		mapActions.put("RegistroPonto", new RegistrarPontoAction());
		mapActions.put("RegistroFuncionario", new FuncionarioAction());
		mapActions.put("ConsultarRegistros", new ConsultarRegistrosAction());
		mapActions.put("Autenticar", new AutenticarAction());
		mapActions.put("AtualizarRegistros", new AtualizarRegistrosAction());
		mapActions.put("CadastroFuncionario", new CadastroFuncionarioAction());
		mapActions.put("PesquisarFuncionario", new PesquisarFuncionarioAction());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String uri = req.getRequestURI();
		ActionResult result = null;
		Action action = mapActions.get(uri.substring((uri.lastIndexOf("/") + 1), uri.lastIndexOf(".")));
		RequestDispatcher rd = null;
		
		if (action != null){
			result = action.execute(req, resp);
			
			if(result != null) {
				req.setAttribute("errorMessages", result.getErrorMessages());
				req.setAttribute("infoMessages", result.getInfoMessages());
				req.setAttribute("parametros", result.getParametros());
			
				rd = req.getRequestDispatcher(result.getUrl());
			}
		}
		else{
			rd = req.getRequestDispatcher("/erro404.jsp");
		}
		if(rd != null) {
			rd.forward(req, resp);
		}
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
}
